package com.iris.live.services.services.impl;

import com.iris.live.services.common.DateFormatUtils;
import com.iris.live.services.common.StringUtils;
import com.iris.live.services.data.models.Lsh先享后选设置Model;
import com.iris.live.services.data.models.Lsh金融设置Model;
import com.iris.live.services.data.models.Lsh金融设置适用车型Model;
import com.iris.live.services.data.models.TVehicleModelMapModel;
import com.iris.live.services.data.repositories.*;
import com.iris.live.services.models.ResultData;
import com.iris.live.services.services.ImportFinanceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.transaction.interceptor.TransactionInterceptor;

import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by lusong on 2017/7/10.
 */
@Service
public class ImportFinanceServiceImpl implements ImportFinanceService {

    private Logger logger = LoggerFactory.getLogger(ImportFinanceServiceImpl.class);

    @Autowired
    private Lsh金融设置Repository lsh金融设置Repository;

    @Autowired
    private LSH金融设置适用车型Repository lsh金融设置适用车型Repository;

    @Autowired
    private TVehicleModelMapRepository tVehicleModelMapRepository;

    @Autowired
    private Lsh先享后选设置Repository lsh先享后选设置Repository;

    @Autowired
    private Lsh车型Repository lsh车型Repository;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultData insertLiveToLsh(List<Map<String, Object>> list) throws Exception {
        ResultData resultData = new ResultData("false", null, null);
        StringBuffer message = new StringBuffer();
        message.append("错误信息:\n");
        List<TVehicleModelMapModel> tVehicleModelMapModels = new ArrayList<>();
        if (list != null) {
            Map mapCheck = new HashMap();
            for (Object object : list) {
                if (object != null) {
                    Map map = (Map) object;
                    String venderId = map.get("奔驰金融&奔驰租赁产品车型") == null ? null : map.get("奔驰金融&奔驰租赁产品车型").toString().trim();
                    String lshCarId = map.get("LiVE") == null ? null : map.get("LiVE").toString().trim();
                    if (StringUtils.isNullOrBlank(lshCarId) && StringUtils.isNullOrBlank(venderId)) {
                        break;
                    } else {
                        if (StringUtils.isNullOrBlank(lshCarId)) {
                            message.append("奔驰金融&奔驰租赁产品车型:" + venderId + "LiVE为空\n");
                            continue;
                        }
                        if (StringUtils.isNullOrBlank(venderId)) {
                            message.append("LiVE车型:" + lshCarId + "奔驰金融&奔驰租赁产品车型为空\n");
                            continue;
                        }
                    }
                    if (!StringUtils.isNullOrBlank(mapCheck.get(venderId)) && mapCheck.get(venderId).equals(lshCarId)) {
                        message.append("奔驰金融&奔驰租赁产品车型:" + venderId + ",LiVE车型:" + lshCarId + ",重复车型信息\n");
                        continue;
                    }
                    mapCheck.put(venderId, lshCarId);
                    List<Integer> list1 = lsh车型Repository.queryCarCodeByCarDetail(lshCarId);
                    if (list1 == null || list1.isEmpty()) {
                        message.append("奔驰金融&奔驰租赁产品车型:" + venderId + ",LiVE车型:" + lshCarId + ",未找到相关车型信息\n");
                    }
                    for (int i = 0; i < list1.size(); i++) {
                        TVehicleModelMapModel tVehicleModelMapModel = new TVehicleModelMapModel();
                        tVehicleModelMapModel.setCarId(list1.get(i));
                        tVehicleModelMapModel.setVenderId(venderId);
                        tVehicleModelMapModel.setUpdateTime(new Timestamp(new Date().getTime()));
                        tVehicleModelMapModels.add(tVehicleModelMapModel);
                    }
                } else {
                    message.append("导入excel为空\n");
                }
            }
        } else {
            message.append("导入excel为空\n");
        }
        if ("错误信息:\n".equals(message.toString())) {
            resultData.setResult("true");
            tVehicleModelMapRepository.deleteAll();
            tVehicleModelMapRepository.save(tVehicleModelMapModels);
        } else {
            resultData.setMessage(message.toString());
        }
        return resultData;
    }

    /**
     * @param list
     * @param permit
     * @param startDate
     * @param endDate
     * @param type      1:奔驰金融;2:smart金融
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultData insertFinanceSetUp(List<Map<String, Object>> list, String permit, String username, String startDate, String endDate, String type) throws Exception {
        ResultData resultData = new ResultData("false", null, null);
        StringBuffer message = new StringBuffer();
        message.append("错误信息:\n");
        if (list == null || list.isEmpty()) {
            resultData.setMessage("导入excel为空\n");
            return resultData;
        }
        if (startDate == null || "".equals(startDate) || endDate == null || "".equals(endDate)) {
            message.append("未选择启用日期或结束日期\n");
            resultData.setMessage(message.toString());
            return resultData;
        }

        Map<String, String> carTypeMap = getTVehicleModelMap();
        //奔驰金融首付比例 普通期数：20;星时贷：50
        //smart金融首付比例 待定
        int downRate = 20, downRateOther = 50;
        java.sql.Date startDateSQL = DateFormatUtils.parseStrToSqlDate(startDate),
                endDateSQL = DateFormatUtils.parseStrToSqlDate(endDate);
        int index = 1;
        for (Map<String, Object> map : list) {
            String venderId = map.get("厂家编号") == null ? null : map.get("厂家编号").toString().trim();
            if (venderId == null || "".equals(venderId)) {
                break;
            }
            String carIds = carTypeMap.get(venderId);
            if (StringUtils.isNullOrBlank(carIds)) {
                logger.error("奔驰金融&奔驰租赁产品车型" + venderId + "未找到LiVE匹配车型");
                message.append("奔驰金融&奔驰租赁产品车型：" + venderId + "\n");
                continue;
            }
            String msrp = map.get("MSRP") == null ? null : map.get("MSRP").toString();
            String yearRate12 = map.get("12") == null ? null : map.get("12").toString();
            String yearRate24 = map.get("24") == null ? null : map.get("24").toString();
            String yearRate36 = map.get("36") == null ? null : map.get("36").toString();
            String yearRate48 = map.get("48") == null ? null : map.get("48").toString();
            String yearRate60 = map.get("60") == null ? null : map.get("60").toString();
            String yearRateOther = map.get("星时贷") == null ? null : map.get("星时贷").toString();
            String productId12 = map.get("12期产品编号") == null ? null : map.get("12期产品编号").toString();
            String productId24 = map.get("24期产品编号") == null ? null : map.get("24期产品编号").toString();
            String productId36 = map.get("36期产品编号") == null ? null : map.get("36期产品编号").toString();
            String productId48 = map.get("48期产品编号") == null ? null : map.get("48期产品编号").toString();
            String productId60 = map.get("60期产品编号") == null ? null : map.get("60期产品编号").toString();
            String productIdOther = map.get("星时贷产品编号") == null ? null : map.get("星时贷产品编号").toString();
            String financingSubsidyRate = map.get("financingSubsidyRate") == null ? null : map.get("financingSubsidyRate").toString();


            Lsh金融设置Model model12 = null;
            //保存 12 期 金融产品
            if ("1".equals(type)) {
                model12 = saveAMGFinanceDiscountProduct(1, "奔驰金融", startDateSQL, endDateSQL, yearRate12, "利率", 50, "是", 50,
                        "12", permit, "贴息产品", productId12, "汽车分期", "金融贷款", "抵押", "厂家/金融机构贴息", username, index++);
            } else {
                model12 = saveAMGFinanceDiscountProduct(1, "奔驰金融", startDateSQL, endDateSQL, yearRate12, "利率", 20, "否", 0,
                        "12", permit, "贴息产品", productId12, "汽车分期", "金融贷款", "抵押", "厂家/金融机构贴息", username, index++);
            }
            //保存 24 期 金融产品
            Lsh金融设置Model model24 = saveAMGFinanceDiscountProduct(1, "奔驰金融", startDateSQL, endDateSQL, yearRate24, "利率", 20, "否", 0,
                    "24", permit, "贴息产品", productId24, "汽车分期", "金融贷款", "抵押", "厂家/金融机构贴息", username, index++);

            //保存 36 期 金融产品
            Lsh金融设置Model model36 = saveAMGFinanceDiscountProduct(1, "奔驰金融", startDateSQL, endDateSQL, yearRate36, "利率", 20, "否", 0,
                    "36", permit, "贴息产品", productId36, "汽车分期", "金融贷款", "抵押", "厂家/金融机构贴息", username, index++);
            //保存 48 期 金融产品
            Lsh金融设置Model model48 = saveAMGFinanceDiscountProduct(1, "奔驰金融", startDateSQL, endDateSQL, yearRate48, "利率", 20, "否", 0,
                    "48", permit, "贴息产品", productId48, "汽车分期", "金融贷款", "抵押", "厂家/金融机构贴息", username, index++);
            //保存 60 期 金融产品
            Lsh金融设置Model model60 = saveAMGFinanceDiscountProduct(1, "奔驰金融", startDateSQL, endDateSQL, yearRate60, "利率", 20, "否", 0,
                    "60", permit, "贴息产品", productId60, "汽车分期", "金融贷款", "抵押", "厂家/金融机构贴息", username, index++);
            //保存 星时贷 金融产品
            Lsh金融设置Model modelOther = saveAMGFinanceDiscountProduct(1, "奔驰金融", startDateSQL, endDateSQL, yearRateOther, "利率", 50, "否", 0,
                    "36", permit, "贴息产品", productIdOther, "汽车分期", "金融贷款", "抵押", "厂家/金融机构贴息", username, index++);

            List<Integer> listFinanceId = new ArrayList<>();
            if (model12 != null) {
                listFinanceId.add(model12.get金融编号());
            }
            if (model24 != null) {
                listFinanceId.add(model24.get金融编号());
            }
            if (model36 != null) {
                listFinanceId.add(model36.get金融编号());
            }
            if (model48 != null) {
                listFinanceId.add(model48.get金融编号());
            }
            if (model60 != null) {
                listFinanceId.add(model60.get金融编号());
            }
            if (modelOther != null) {
                listFinanceId.add(modelOther.get金融编号());
            }

            String[] carArr = carIds.split(",");
            saveApplyCarType(carArr, listFinanceId);
        }
        if ("错误信息:\n".equals(message.toString())) {
            resultData.setResult("true");
        } else {
            resultData.setMessage(message.toString());
            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
        }
        return resultData;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultData insertAfterTheFirstSelection(List<Map<String, Object>> list, String permit, String username,
                                                   String startDate, String endDate, String type) throws Exception {
        ResultData resultData = new ResultData("false", null, null);
        StringBuffer message = new StringBuffer();
        message.append("错误信息:\n");
        if (list == null || list.isEmpty()) {
            resultData.setMessage("导入excel为空\n");
            return resultData;
        }
        if (startDate == null || "".equals(startDate) || endDate == null || "".equals(endDate)) {
            message.append("未选择启用日期或结束日期\n");
            resultData.setMessage(message.toString());
            return resultData;
        }
        java.sql.Date startDateSQL = DateFormatUtils.parseStrToSqlDate(startDate),
                endDateSQL = DateFormatUtils.parseStrToSqlDate(endDate);

        Map<String, String> carTypeMap = getTVehicleModelMap();
        int index = 1;
        for (Map<String, Object> map : list) {
            String venderId = map.get("厂家编号") == null ? null : map.get("厂家编号").toString().trim();
            if (StringUtils.isNullOrBlank(venderId)) {
                break;
            }
            String carIds = carTypeMap.get(venderId);
            if (StringUtils.isNullOrBlank(carIds)) {
                logger.error("奔驰金融&奔驰租赁产品车型" + venderId + "未找到LiVE匹配车型");
                message.append("奔驰金融&奔驰租赁产品车型：" + venderId + "\n");
                continue;
            }
            String msrp = map.get("MSRP") == null ? null : map.get("MSRP").toString();
            if (StringUtils.isNullOrBlank(msrp)) {
                message.append("车型：" + venderId + ",MSRP为空\n");
            }
            String maintainValue24_10000 = map.get("24-10000利率") == null ? null : map.get("24-10000利率").toString();
            String maintainValue24_15000 = map.get("24-15000利率") == null ? null : map.get("24-15000利率").toString();
            String maintainValue24_20000 = map.get("24-20000利率") == null ? null : map.get("24-20000利率").toString();
            String maintainValue24_25000 = map.get("24-25000利率") == null ? null : map.get("24-25000利率").toString();
            String maintainValue36_10000 = map.get("36-10000利率") == null ? null : map.get("36-10000利率").toString();
            String maintainValue36_15000 = map.get("36-15000利率") == null ? null : map.get("36-15000利率").toString();
            String maintainValue36_20000 = map.get("36-20000利率") == null ? null : map.get("36-20000利率").toString();
            String maintainValue36_25000 = map.get("36-25000利率") == null ? null : map.get("36-25000利率").toString();
            String securityDepositRatio = map.get("保证金比例") == null ? null : map.get("保证金比例").toString();
            String agilityYearRate24 = map.get("24") == null ? null : map.get("24").toString();//smart 先享后选 利率 || 奔驰  先享后选 普通 利率
            String agilityYearRate36 = map.get("36") == null ? null : map.get("36").toString();//smart 先享后选 利率 || 奔驰  先享后选 普通 利率
            String productId = map.get("金融产品编码") == null ? null : map.get("金融产品编码").toString();
            String yearRate24 = map.get("ordinary 24") == null ? null : map.get("ordinary 24").toString();//奔驰  先享后选 星时享 利率
            String yearRate36 = map.get("ordinary 36") == null ? null : map.get("ordinary 36").toString();//奔驰  先享后选 星时享 利率

            int financeId = 0;
            Lsh金融设置Model lsh金融设置ModelAgility = null;
            Lsh金融设置Model lsh金融设置ModelExpress = null;
            if ("3".equals(type)) {
                if (StringUtils.isNullOrBlank(productId)) {
                    String quarter = getQuarterOfFinanceProduct(startDate, endDate);
                    if (StringUtils.isNullOrBlank(quarter)) {
                        logger.error("导入MB先享后选产品---启用日期或结束日期选择有误");
                        resultData.setMessage("导入MB先享后选产品---启用日期或结束日期选择有误");
                        return resultData;
                    }
                    productId = "CPN MB_GFV_" + quarter;
                }
                //保存 奔驰先享后选 标准产品， 非贴息
                lsh金融设置ModelAgility = saveAMGFinanceDiscountProduct(2, "奔驰租赁", startDateSQL, endDateSQL, "0", "利率", 0, "否", 0,
                        "0", permit, "标准产品", productId, "汽车分期", "先享后选", "抵押", "非贴息", username, index++);
                //保存 奔驰先享后选 贴息产品， 厂家/金融机构贴息
                lsh金融设置ModelExpress  = saveAMGFinanceDiscountProduct(2, "奔驰租赁", startDateSQL, endDateSQL, "0", "利率", 0, "否", 0,
                        "0", permit, "贴息产品", productId, "汽车分期", "先享后选", "抵押", "厂家/金融机构贴息", username, index++);
                //保存 先享后选设置  利率状态  普通
                if (lsh金融设置ModelAgility != null) {
                    financeId = lsh金融设置ModelAgility.get金融编号();
                    addDefaultValue(username, financeId, 24, agilityYearRate24, 0, msrp, maintainValue24_10000, 10000);
                    addDefaultValue(username, financeId, 24, agilityYearRate24, 0, msrp, maintainValue24_15000, 15000);
                    addDefaultValue(username, financeId, 24, agilityYearRate24, 0, msrp, maintainValue24_20000, 20000);
                    addDefaultValue(username, financeId, 24, agilityYearRate24, 0, msrp, maintainValue24_25000, 25000);
                    addDefaultValue(username, financeId, 36, agilityYearRate36, 0, msrp, maintainValue36_10000, 10000);
                    addDefaultValue(username, financeId, 36, agilityYearRate36, 0, msrp, maintainValue36_15000, 15000);
                    addDefaultValue(username, financeId, 36, agilityYearRate36, 0, msrp, maintainValue36_20000, 20000);
                    addDefaultValue(username, financeId, 36, agilityYearRate36, 0, msrp, maintainValue36_25000, 25000);
                }
                //保存 先享后选设置  利率状态  星时享
                if (lsh金融设置ModelExpress != null) {
                    financeId = lsh金融设置ModelExpress.get金融编号();
                    addDefaultValue(username, financeId, 24, yearRate24, 1, msrp, maintainValue24_10000, 10000);
                    addDefaultValue(username, financeId, 24, yearRate24, 1, msrp, maintainValue24_15000, 15000);
                    addDefaultValue(username, financeId, 24, yearRate24, 1, msrp, maintainValue24_20000, 20000);
                    addDefaultValue(username, financeId, 24, yearRate24, 1, msrp, maintainValue24_25000, 25000);
                    addDefaultValue(username, financeId, 36, yearRate36, 1, msrp, maintainValue36_10000, 10000);
                    addDefaultValue(username, financeId, 36, yearRate36, 1, msrp, maintainValue36_15000, 15000);
                    addDefaultValue(username, financeId, 36, yearRate36, 1, msrp, maintainValue36_20000, 20000);
                    addDefaultValue(username, financeId, 36, yearRate36, 1, msrp, maintainValue36_25000, 25000);
                }
            } else if ("4".equals(type)) {
                lsh金融设置ModelExpress  = saveAMGFinanceDiscountProduct(2, "奔驰租赁", startDateSQL, endDateSQL, "0", "利率", 0, "否", 0,
                        "0", permit, "贴息产品", productId, "汽车分期", "先享后选", "抵押", "厂家/金融机构贴息", username, index++);
                if (lsh金融设置ModelExpress != null) {
                    financeId = lsh金融设置ModelExpress.get金融编号();
                    addDefaultValue(username, financeId, 24, agilityYearRate24, 0, msrp, maintainValue24_10000, 10000);
                    addDefaultValue(username, financeId, 24, agilityYearRate24, 0, msrp, maintainValue24_15000, 15000);
                    addDefaultValue(username, financeId, 24, agilityYearRate24, 0, msrp, maintainValue24_20000, 20000);
                    addDefaultValue(username, financeId, 24, agilityYearRate24, 0, msrp, maintainValue24_25000, 25000);
                    addDefaultValue(username, financeId, 36, agilityYearRate36, 0, msrp, maintainValue36_10000, 10000);
                    addDefaultValue(username, financeId, 36, agilityYearRate36, 0, msrp, maintainValue36_15000, 15000);
                    addDefaultValue(username, financeId, 36, agilityYearRate36, 0, msrp, maintainValue36_20000, 20000);
                    addDefaultValue(username, financeId, 36, agilityYearRate36, 0, msrp, maintainValue36_25000, 25000);
                }
            }

            List<Integer> l = new ArrayList<>();
            if (lsh金融设置ModelExpress != null) {
                l.add(lsh金融设置ModelExpress.get金融编号());
            }
            if (lsh金融设置ModelAgility != null) {
                l.add(lsh金融设置ModelAgility.get金融编号());
            }
            //保存 金融适用车型
            String[] carIdArr = carIds.split(",");
            saveApplyCarType(carIdArr, l);
        }
        if ("错误信息:\n".equals(message.toString())) {
            resultData.setResult("true");
        } else {
            resultData.setMessage(message.toString());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return resultData;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultData leadingInAMGFinanceDiscount (String permit, String username, String startDate, String endDate, List list) throws Exception {
        ResultData resultData = new ResultData("false", null, null);
        if (list == null || list.isEmpty()) {
            logger.error("导入AMG金融贴息产品---未获取到金融贴息产品信息");
            resultData.setMessage("导入AMG金融贴息产品---未获取到金融贴息产品信息");
            return resultData;
        }
        if (startDate == null || "".equals(startDate) || endDate == null || "".equals(endDate)) {
            logger.error("导入AMG金融贴息产品---未选择启用日期或结束日期");
            resultData.setMessage("导入AMG金融贴息产品---未选择启用日期或结束日期");
            return resultData;
        }

        java.sql.Date startDateSQL = DateFormatUtils.parseStrToSqlDate(startDate),
                endDateSQL = DateFormatUtils.parseStrToSqlDate(endDate);
        int index = 1;

        Map<String, String> vehicleModelMap = getTVehicleModelMap();
        String quarter = getQuarterOfFinanceProduct(startDate, endDate);
        if (StringUtils.isNullOrBlank(quarter)) {
            logger.error("导入AMG金融贴息产品---启用日期或结束日期选择有误");
            resultData.setMessage("导入AMG金融贴息产品---启用日期或结束日期选择有误");
            return resultData;
        }
        //12期产品编码
        String twelveProductNumSystem = "CPN BP AMG_" + quarter + "_12m_Balloon";
        //24期产品编码
        String twentyFourProductNumSystem = "CPN BP AMG_" + quarter + "_12m - 48m_ Low DP";
        //36期产品编码
        String thirtySixProductNumSystem = twentyFourProductNumSystem;
        //48期产品编码
        String fortyEightProductNumSystem = twentyFourProductNumSystem;
        //星时贷产品编码
        String starTimeLoanProductNumSystem = "CPN BP AMG_" + quarter + "_36m_0.99_Star Approval";
        //记录 不符合规则信息
        StringBuffer message = new StringBuffer();
        message.append("错误信息:\n");
        for (Object o : list) {
            Map map = (Map) o;
            String venderId = null;
            String carIds = null;
            if (StringUtils.isNullOrBlank(map.get("carType"))) {
                logger.error("导入AMG金融贴息产品---奔驰金融&奔驰租赁产品车型为空");
                break;
            } else {
                venderId = map.get("carType").toString().trim();
            }
            carIds = vehicleModelMap.get(venderId.trim());
            if (StringUtils.isNullOrBlank(carIds)) {
                logger.error("导入AMG金融贴息产品---奔驰金融&奔驰租赁产品车型" + venderId + "未找到LiVE匹配车型");
                message.append("奔驰金融&奔驰租赁产品车型：" + venderId + "\n");
                continue;
            }
            String msrp = map.get("msrp") == null ? null : map.get("msrp").toString();
            String yearRate12 = map.get("twelve") == null ? null : map.get("twelve").toString();
            String yearRate24 = map.get("twentyFour") == null ? null : map.get("twentyFour").toString();
            String yearRate36 = map.get("thirtySix") == null ? null : map.get("thirtySix").toString();
            String yearRate48 = map.get("fortyEight") == null ? null : map.get("fortyEight").toString();
            String billRate = map.get("billRate") == null ? null : map.get("billRate").toString();
            String starTimeLoanRate = map.get("starTimeLoan") == null ? null : map.get("starTimeLoan").toString();

            String twelveProductNum = StringUtils.isNullOrBlank(map.get("twelveProductNum")) ? twelveProductNumSystem : map.get("twelveProductNum").toString();
            String twentyFourProductNum = StringUtils.isNullOrBlank(map.get("twentyFourProductNum")) ? twentyFourProductNumSystem : map.get("twentyFourProductNum").toString();
            String thirtySixProductNum = StringUtils.isNullOrBlank(map.get("thirtySixProductNum")) ? thirtySixProductNumSystem : map.get("thirtySixProductNum").toString();
            String fortyEightProductNum = StringUtils.isNullOrBlank(map.get("fortyEightProductNum")) ? fortyEightProductNumSystem : map.get("fortyEightProductNum").toString();
            String starTimeLoanProductNum = StringUtils.isNullOrBlank(map.get("starTimeLoanProductNum")) ? starTimeLoanProductNumSystem : map.get("starTimeLoanProductNum").toString();

            Lsh金融设置Model model12 = saveAMGFinanceDiscountProduct(1, "奔驰金融", startDateSQL, endDateSQL, yearRate12, "利率", 50, "是", 50,
                    "12", permit, "贴息产品", twelveProductNum, "汽车分期", "金融贷款", "抵押", "厂家/金融机构贴息", username, index++);
            Lsh金融设置Model model24 = saveAMGFinanceDiscountProduct(1, "奔驰金融", startDateSQL, endDateSQL, yearRate24, "利率", 20, "否", 0,
                    "24", permit, "贴息产品", twentyFourProductNum, "汽车分期", "金融贷款", "抵押", "厂家/金融机构贴息", username, index++);
            Lsh金融设置Model model36 = saveAMGFinanceDiscountProduct(1, "奔驰金融", startDateSQL, endDateSQL, yearRate36, "利率", 20, "否", 0,
                    "36", permit, "贴息产品", thirtySixProductNum, "汽车分期", "金融贷款", "抵押", "厂家/金融机构贴息", username, index++);
            Lsh金融设置Model model48 = saveAMGFinanceDiscountProduct(1, "奔驰金融", startDateSQL, endDateSQL, yearRate48, "利率", 20, "否", 0,
                    "48", permit, "贴息产品", fortyEightProductNum, "汽车分期", "金融贷款", "抵押", "厂家/金融机构贴息", username, index++);
            Lsh金融设置Model modelOther = saveAMGFinanceDiscountProduct(1, "奔驰金融", startDateSQL, endDateSQL, starTimeLoanRate, "利率", 50, "否", 0,
                    "36", permit, "贴息产品", starTimeLoanProductNum, "汽车分期", "金融贷款", "抵押", "厂家/金融机构贴息", username, index++);

            List<Integer> listFinanceId = new ArrayList<>();
            if (model12 != null) {
                listFinanceId.add(model12.get金融编号());
            }
            if (model24 != null) {
                listFinanceId.add(model24.get金融编号());
            }
            if (model36 != null) {
                listFinanceId.add(model36.get金融编号());
            }
            if (model48 != null) {
                listFinanceId.add(model48.get金融编号());
            }
            if (modelOther != null) {
                listFinanceId.add(modelOther.get金融编号());
            }

            String[] carIdArr = carIds.split(",");
            saveApplyCarType(carIdArr, listFinanceId);
        }
        if ("错误信息:\n".equals(message.toString())) {
            resultData.setResult("true");
        } else {
            resultData.setMessage(message.toString());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return resultData;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultData leadingInAMGEnjoy (String permit, String username, String startDate, String endDate, List list) throws Exception {
        ResultData resultData = new ResultData("false", null, null);
        if (list == null || list.isEmpty()) {
            logger.error("导入AMG先享后选产品---未获取到先享后选产品信息");
            resultData.setMessage("导入AMG先享后选产品---未获取到先享后选产品信息");
            return resultData;
        }
        if (startDate == null || "".equals(startDate) || endDate == null || "".equals(endDate)) {
            logger.error("导入AMG先享后选产品---未选择启用日期或结束日期");
            resultData.setMessage("导入AMG先享后选产品---未选择启用日期或结束日期");
            return resultData;
        }

        java.sql.Date startDateSQL = DateFormatUtils.parseStrToSqlDate(startDate),
                endDateSQL = DateFormatUtils.parseStrToSqlDate(endDate);
        int index = 1;

        Map<String, String> vehicleModelMap = getTVehicleModelMap();

        //记录 不符合规则信息
        StringBuffer message = new StringBuffer();
        message.append("错误信息:\n");
        for (Object o : list) {
            Map map = (Map) o;
            String venderId = null;
            String carIds = null;
            if (StringUtils.isNullOrBlank(map.get("carType"))) {
                logger.error("导入AMG先享后选产品---奔驰金融&奔驰租赁产品车型为空");
                break;
            } else {
                venderId = map.get("carType").toString().trim();
            }
            carIds = vehicleModelMap.get(venderId.trim());
            if (StringUtils.isNullOrBlank(carIds)) {
                logger.error("导入AMG先享后选产品---奔驰金融&奔驰租赁产品车型" + venderId + "未找到LiVE匹配车型");
                message.append("奔驰金融&奔驰租赁产品车型：" + venderId + "\n");
                continue;
            }
            String msrp = map.get("msrp") == null ? null : map.get("msrp").toString();
            String yearRate24 = map.get("twentyFourRate") == null ? null : map.get("twentyFourRate").toString();
            String yearRate36 = map.get("thirtySixRate") == null ? null : map.get("thirtySixRate").toString();
            String twentyFourHedgeRatio15 = map.get("twentyFourHedgeRatio15") == null ? null : map.get("twentyFourHedgeRatio15").toString();
            String twentyFourHedgeRatio20 = map.get("twentyFourHedgeRatio20") == null ? null : map.get("twentyFourHedgeRatio20").toString();
            String twentyFourHedgeRatio25 = map.get("twentyFourHedgeRatio25") == null ? null : map.get("twentyFourHedgeRatio25").toString();
            String thirtySixHedgeRatio15 = map.get("thirtySixHedgeRatio15") == null ? null : map.get("thirtySixHedgeRatio15").toString();
            String thirtySixHedgeRatio20 = map.get("thirtySixHedgeRatio20") == null ? null : map.get("thirtySixHedgeRatio20").toString();
            String thirtySixHedgeRatio25 = map.get("thirtySixHedgeRatio25") == null ? null : map.get("thirtySixHedgeRatio25").toString();
            String subsidyTMSRP24 = map.get("subsidyTMSRP24") == null ? null : map.get("subsidyTMSRP24").toString();
            String subsidyTMSRP36 = map.get("subsidyTMSRP36") == null ? null : map.get("subsidyTMSRP36").toString();
            String productId = map.get("productId") == null ? null : map.get("productId").toString();

            if (StringUtils.isNullOrBlank(productId)) {
                String quarter = getQuarterOfFinanceProduct(startDate, endDate);
                if (StringUtils.isNullOrBlank(quarter)) {
                    logger.error("导入MB先享后选产品---启用日期或结束日期选择有误");
                    resultData.setMessage("导入MB先享后选产品---启用日期或结束日期选择有误");
                    return resultData;
                }
                productId = "CPN AMG_GFV_" + quarter;
            }
            //保存 AMG先享后选 贴息产品， 厂家/金融机构贴息
            Lsh金融设置Model lsh金融设置ModelExpress  = saveAMGFinanceDiscountProduct(2, "奔驰租赁", startDateSQL, endDateSQL, "0", "利率", 0, "否", 0,
                    "0", permit, "贴息产品", productId, "汽车分期", "先享后选", "抵押", "厂家/金融机构贴息", username, index++);

            //保存 先享后选设置  利率状态  星时享
            if (lsh金融设置ModelExpress != null) {
                int financeId = lsh金融设置ModelExpress.get金融编号();
                addDefaultValue(username, financeId, 24, yearRate24, 1, msrp, twentyFourHedgeRatio15, 15000);
                addDefaultValue(username, financeId, 24, yearRate24, 1, msrp, twentyFourHedgeRatio20, 20000);
                addDefaultValue(username, financeId, 24, yearRate24, 1, msrp, twentyFourHedgeRatio25, 25000);
                addDefaultValue(username, financeId, 36, yearRate36, 1, msrp, thirtySixHedgeRatio15, 15000);
                addDefaultValue(username, financeId, 36, yearRate36, 1, msrp, thirtySixHedgeRatio20, 20000);
                addDefaultValue(username, financeId, 36, yearRate36, 1, msrp, thirtySixHedgeRatio25, 25000);
            }

            //保存金融产品适用车型
            List<Integer> listFinanceId = new ArrayList<>();
            if (lsh金融设置ModelExpress != null) {
                listFinanceId.add(lsh金融设置ModelExpress.get金融编号());
            }
            String[] carIdArr = carIds.split(",");
            saveApplyCarType(carIdArr, listFinanceId);
        }
        if ("错误信息:\n".equals(message.toString())) {
            resultData.setResult("true");
        } else {
            resultData.setMessage(message.toString());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return resultData;
    }

    //获取 奔驰金融&奔驰租赁产品车型 -- LiVE 车型 Map
    private Map<String, String> getTVehicleModelMap () {
        Map<String, String> map = null;
        List<TVehicleModelMapModel> list = tVehicleModelMapRepository.findAll();
        if (list == null || list.isEmpty()) {
            return map;
        }
        map = new HashMap<>();
        for (TVehicleModelMapModel model : list) {
            if (model == null || StringUtils.isNullOrBlank(model.getCarId()) || StringUtils.isNullOrBlank(model.getVenderId())) {
                continue;
            }
            if (StringUtils.isNullOrBlank(map.get(model.getVenderId()))) {
                map.put(model.getVenderId(), model.getCarId() + "");
            } else {
                map.put(model.getVenderId(), map.get(model.getVenderId()) + "," + model.getCarId());
            }
        }
        return map;
    }

    //获取导入的 金融产品  所属季度
    private String getQuarterOfFinanceProduct (String startDate, String endDate) {
        String date1 = null, date2 = null;
        String year = startDate.substring(0, 4);
        // 判断 是否为第一季度
        date1 = year + "-01-01";
        date2 = year + "-03-31";
        if (DateFormatUtils.getFormatDate(startDate, "yyyy-MM-dd").getTime() >= DateFormatUtils.getFormatDate(date1, "yyyy-MM-dd").getTime() &&
                DateFormatUtils.getFormatDate(endDate, "yyyy-MM-dd").getTime() <= DateFormatUtils.getFormatDate(date2, "yyyy-MM-dd").getTime()) {
            return year + " Q1";
        }
        // 判断 是否为第二季度
        date1 = year + "-04-01";
        date2 = year + "-06-30";
        if (DateFormatUtils.getFormatDate(startDate, "yyyy-MM-dd").getTime() >= DateFormatUtils.getFormatDate(date1, "yyyy-MM-dd").getTime() &&
                DateFormatUtils.getFormatDate(endDate, "yyyy-MM-dd").getTime() <= DateFormatUtils.getFormatDate(date2, "yyyy-MM-dd").getTime()) {
            return year + " Q2";
        }
        // 判断 是否为第三季度
        date1 = year + "-07-01";
        date2 = year + "-09-30";
        if (DateFormatUtils.getFormatDate(startDate, "yyyy-MM-dd").getTime() >= DateFormatUtils.getFormatDate(date1, "yyyy-MM-dd").getTime() &&
                DateFormatUtils.getFormatDate(endDate, "yyyy-MM-dd").getTime() <= DateFormatUtils.getFormatDate(date2, "yyyy-MM-dd").getTime()) {
            return year + " Q3";
        }
        // 判断 是否为第四季度
        date1 = year + "-10-01";
        date2 = year + "-12-31";
        if (DateFormatUtils.getFormatDate(startDate, "yyyy-MM-dd").getTime() >= DateFormatUtils.getFormatDate(date1, "yyyy-MM-dd").getTime() &&
                DateFormatUtils.getFormatDate(endDate, "yyyy-MM-dd").getTime() <= DateFormatUtils.getFormatDate(date2, "yyyy-MM-dd").getTime()) {
            return year + " Q4";
        }
        return null;
    }

    private Lsh金融设置Model saveAMGFinanceDiscountProduct (int financeCompanyId, String financeProductName, java.sql.Date startDate, java.sql.Date endDate,
                                                        String yearRate, String rateState, int downPayRate, String isFinalPay, int superiorFinalPayRate,
                                                        String installments, String permit, String productType, String productNum, String serviceType,
                                                        String morgageType, String loanType, String discountType, String username, int index) {
        if (yearRate == null || "".equals(yearRate) || "N.A.".equals(yearRate) || "不适用".equals(yearRate)) {
            return null;
        }
        if (productNum == null || "".equals(productNum) || "N.A.".equals(productNum) || "不适用".equals(productNum)) {
            return null;
        }
        Lsh金融设置Model lsh金融设置Model = new Lsh金融设置Model();
        DecimalFormat df = new DecimalFormat("#0.00");
        double yearRateDouble = Double.parseDouble(yearRate) * 100;

        lsh金融设置Model.set金融机构编号(financeCompanyId);
        lsh金融设置Model.set金融产品名称(financeProductName);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String financeLevel = username + sdf.format(new Date()) + "_" + index;
        lsh金融设置Model.set金融系列(financeLevel);
        lsh金融设置Model.set开始日期(startDate);
        lsh金融设置Model.set结束日期(endDate);
        lsh金融设置Model.set年利率(df.format(yearRateDouble));
        lsh金融设置Model.set利率状态(rateState);
        lsh金融设置Model.set最低首付比例(downPayRate);
        lsh金融设置Model.set是否尾款(isFinalPay);
        lsh金融设置Model.set最高尾款比例(superiorFinalPayRate);
        lsh金融设置Model.set期数(installments);
        lsh金融设置Model.set许可(permit);
        lsh金融设置Model.set产品编码(productNum);
        lsh金融设置Model.set贷款类型(loanType);
        lsh金融设置Model.set贴息类型(discountType);
        lsh金融设置Model.set产品分类(productType);
        lsh金融设置Model.set业务类型(serviceType);
        lsh金融设置Model.set按揭类型(morgageType);

        lsh金融设置Model.set保证金比例(0);
        lsh金融设置Model.set是否固定("否");
        lsh金融设置Model.set贴息利率("0");
        lsh金融设置Model.set贴息利率B("0");
        lsh金融设置Model.set是否热销("否");
        lsh金融设置Model.set是否有效("是");
        lsh金融设置Model.set是否删除("否");
        lsh金融设置Model.set更新账号(username);
        lsh金融设置Model.set更新时间(new Timestamp(new Date().getTime()));
        lsh金融设置Model = lsh金融设置Repository.save(lsh金融设置Model);
        return lsh金融设置Model;
    }

    private Lsh先享后选设置Model addDefaultValue(String username, int financeId, int loanTerm, String yearRate,
                                           int yearRateState, String msrp, String maintainValue, int param) {
        if (yearRate == null || "".equals(yearRate) || "N.A.".equals(yearRate) || "不适用".equals(yearRate)) {
            return null;
        }
        if (maintainValue == null || "".equals(maintainValue) || "N.A.".equals(maintainValue) || "不适用".equals(maintainValue)) {
            return null;
        }
        DecimalFormat df = new DecimalFormat("#0.00");
        Lsh先享后选设置Model lsh先享后选设置Model = new Lsh先享后选设置Model();
        String maintainValueDouble = null;
        double msrpDouble = Double.parseDouble(msrp);
        double maintainDouble = Double.parseDouble(maintainValue);

        lsh先享后选设置Model.set金融编号(financeId);
        lsh先享后选设置Model.set期数(loanTerm);
        lsh先享后选设置Model.set是否固定("是");
        double yearRateDouble = Double.parseDouble(yearRate) * 100;
        lsh先享后选设置Model.set年利率(df.format(yearRateDouble));
        lsh先享后选设置Model.set利率类型(yearRateState);

        if (maintainDouble <= 1) {
            maintainValueDouble = df.format(maintainDouble * 100);
        } else {
            maintainValueDouble = df.format(maintainDouble / msrpDouble * 100);
        }
        lsh先享后选设置Model.set保值比例(maintainValueDouble);
        lsh先享后选设置Model.set参数(param);
        lsh先享后选设置Model.set更新账号(username);
        lsh先享后选设置Model.set更新时间(new Timestamp(new Date().getTime()));
        lsh先享后选设置Model = lsh先享后选设置Repository.save(lsh先享后选设置Model);
        return lsh先享后选设置Model;
    }

    //保存金融方案适用车型
    private void saveApplyCarType (String[] carIdArr, List<Integer> listFinanceId) {
        for (int j = 0; j < carIdArr.length; j++) {
            if (StringUtils.isNullOrBlank(carIdArr[j])) {
                continue;
            }
            int carId = Integer.parseInt(carIdArr[j]);
            if (listFinanceId != null && !listFinanceId.isEmpty()) {
                List<Lsh金融设置适用车型Model> lsh金融设置适用车型Models = new ArrayList<>();
                for (int i : listFinanceId) {
                    Lsh金融设置适用车型Model lsh金融设置适用车型Model = new Lsh金融设置适用车型Model();
                    lsh金融设置适用车型Model.set适用车型(carId);
                    lsh金融设置适用车型Model.set金融编号(i);
                    lsh金融设置适用车型Models.add(lsh金融设置适用车型Model);
                }
                lsh金融设置适用车型Repository.save(lsh金融设置适用车型Models);
            }
        }
    }
}
